/***************此指令由于通过ctrl进行页面业务查询。因此无法进行独立scop作用域 以后谁想改重新考虑业务重写下****************************/
var PensonSelector=angular.module("PensonSelector",['cgBusy','checklist-model','ui.tree','personnelmanagementS','loadModule'])//'ngAnimate',

//error
PensonSelector.directive('selectorerror',[ function(){
  return {
    link: function($scope, $element, $attrs) {
      $scope.meun=$attrs.nulldata;
    },
    transclude:true,
    replace:true,
    template:"<div class='quexingimg'><img  ng-src='/images/{{meun}}null.png'/></div>",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);

/********************************邮件指令****************************************/
PensonSelector.directive('selectemailmodal',['Msg',function(Msg){
  return {
    scope:{
      ApiData:'=apidata'
    },
    link:function($scope, $element, $attrs){

    },
    transclude:true,
    replace:true,
    templateUrl:"/system/views/personnel/selector/selector_email.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);


/*********************************************************顶级指令*****************************************************************************************/
//将指令继承服务
PensonSelector.directive('selectormodal',['sysUserInfo', function(sysUserInfo){

  return {
    scope:{
      ApiData:'=apidata',
      uploader:"=uploader" 
    },
    link: function($scope, $element, $attrs) {
     //var userinfo={"userId": "d84366cb-c704-4f70-a262-fe27b1e4367e","username":"张三","useraccount":"3048884217@qq.com","userpwd":"123456","organization_ID":"1ac80b5f-52f3-4bcf-8470-9a43f9eccd3f","powerLV":"2"};
     //localStorage.setItem("userinfo",JSON.stringify(userinfo));
    //255e577c-7f67-4a67-abee-2b5c2cd53bce c159a3d3-6965-40f5-893c-41eb39054236    
    /***********************************操作菜单************************/
    //默认全选
    if($scope.ApiData.userMore==undefined){
        $scope.ApiData.userMore=true;
    }

//小窗口下展示
$scope.isSmallMeunShow=false;
$scope.isSmallMeunShowFun=function(){
  return $scope.isSmallMeunShow=!$scope.isSmallMeunShow;
}

$scope.MenuList=[];//显示菜单的集合
//菜单集合源
var MenuListData=[{
  "id":"User",
  "url":"views/personnel/selector/selector_user.html",
  "name":"用户",
  "meunicon":"&#xe664"
},
{
  "id":"Org",
  "url":"views/personnel/selector/selector_org.html",
  "name":"组织机构",
  "meunicon":"&#xe713"
},{

  "id":"Group",
  "url":"views/personnel/selector/selector_group.html",
  "name":"用户组",
  "meunicon":"&#xe91b"
},{

  "id":"Role",
  "url":"views/personnel/selector/selector_role.html",
  "name":"角色",
  "meunicon":"&#xe64d"
},{

  "id":"Email",
  "url":"views/personnel/selector/selector_email.html",
  "name":"邮件邀请"
},{
  "id":"expert",
  "url":"views/personnel/selector/selector_expert.html",
  "name":"专家"
}];

//如果菜单传参为空 显示全部导航
try {
  if ($scope.ApiData.menu==""||$scope.ApiData.menu==undefined) {
    $scope.MenuList = angular.copy(MenuListData);
  }
else//如果菜单传参不为空 显示需要的导航
{

  $scope.MenuContains = function(arr, obj) {  
    var i = arr.length;  
    while (i--) {  
      if (arr[i].id == obj.id) {  
        return i;  
      }  
    }  
    return -1;  
  }

  $scope.ApiData.menu.forEach(function(element, index) {
    var i=$scope.MenuContains(MenuListData,element);
    $scope.MenuList.push(MenuListData[i]);
  });
}

} catch(e) {
  console.log(e);
}

//页面关闭方法
$scope.close=function(){
  $scope.ApiData.ApiOpen=false;
};


//选中方法
$scope.onClickTab = function (tab) {

  $scope.searchText="";
  $scope.currentTab=tab;
  $scope.userListTab=false;
  $scope.orgListTab=false;
  $scope.roleListTab=false;
  $scope.groupListTab=false;
  $scope.emailListTab=false;
  $scope.expertListTab=false;
  switch (tab) {
    case "User":
    $scope.userListTab=true;
    $scope.userList=[];
    $scope.meuntitile="用户";
    
    break;
    case"Org":
    $scope.orgListTab=true;
    $scope.meuntitile="组织机构";
    $scope.meunicon="&#xe713;";    
      //  $scope.GetorgList();
      break;
      case"Role":
      $scope.roleListTab=true;
      $scope.meuntitile="角色";
      $scope.meunicon="&#xe64d;";      
     // $scope.GetroleList();
     break;
     case"Group":
     $scope.groupListTab=true;
     $scope.meuntitile="用户组";
     $scope.meunicon="&#xe91b;";     
     // $scope.GetgroupList();
     break;
     case"Email":
     $scope.emailListTab=true;
     $scope.meuntitile="邮箱";
     break;
     case"expert":
     $scope.expertListTab=true;
     $scope.meuntitile="专家";//班级里已报名的人员
     break;
     default:
     $scope.userListTab=true;
     $scope.meuntitile="用户";
     break;
   }
 }

//修改选中样式
$scope.isActiveTab = function(tabUrl) {
  return tabUrl == $scope.currentTab;
}

//获取鼠标绝对位置
mousePosition =function(ev){
  debugger;
  try {
   if ($scope.ApiData.event) {
    ev=$scope.ApiData.event;
  }
} catch(e) {

}

if (!ev) {ev=window.event;}

if (ev.type!="click") {
 return;
}
var width=0;
var height=0;
  if(ev.pageX || ev.pageY){//firefox、chrome等浏览器
    if (document.documentElement.clientWidth-ev.pageX<450) {
      width= ev.pageX-(450-(document.documentElement.clientWidth-ev.pageX))-20;
    }else {
      width=ev.pageX;
    }
    if (document.documentElement.clientHeight-ev.pageY<480) {
      height= ev.pageY-(480-(document.documentElement.clientHeight -ev.pageY))-20;
    }else {
      height=ev.pageY;
    }
    
    return {"left":width+"px","top":height+"px","position":"fixed"};
  }

  return {// IE浏览器
   "left":ev.clientX + document.body.scrollLeft - document.body.clientLeft,
   "top":ev.clientY + document.body.scrollTop - document.body.clientTop
 };
}

$scope.windowModal=function(){
  $scope.modaltankuang=false;
  $scope.modalsmall=false;
  $scope.modalbig=false;  
  switch ($scope.ApiData.windowModal) {
    case "1":
    $scope.modaltankuang=true;
    break;
    case"2":
    $scope.modalbig=true;
    break;
    case"3":
    $scope.modalsmall=true;
    break;
    case"0":    
    break;
    default:
    $scope.modaltankuang=true;
    break;
  }

  if ($scope.modaltankuang) {
    if (!$scope.ApiData.style||$scope.ApiData.style=="") {
      $scope.ApiData.style=mousePosition();
    }
  }
}
$scope.currentTab= $scope.MenuList[0].id;//默认页面地址
$scope.DataNull=false;//报错显示
$scope.windowModal();//调用模式
$scope.onClickTab($scope.currentTab);
},
transclude:true,
replace:true,
templateUrl:"/system/views/personnel/penson.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);
/*********************************************************用户列表指令***************************************************************/
PensonSelector.directive('selectusermodal',['Msg','sysUserInfo','RequestPopService',function(Msg,sysUserInfo,RS){
  return {
    scope:{
      ApiData:'=apidata',
      userUploader:'=uploader'
    },
    link: function($scope, $element, $attrs) {
$scope.ScreenListVisible=false;//筛选选项列表
$scope.TimeVisible=false;//筛选时间控件显示

$scope.selected=false;//查看已选

//查看已选
$scope.GetCheckList=function(){
    $scope.selected=!$scope.selected;
    if($scope.selected){
        $scope.userList = angular.copy($scope.ApiData.UserList);
    }else{
        $scope.searchBtn();
    }
}
//图标展开
$scope.ShowScreen=function(event){
 event = window.event || event;
 event.stopPropagation();
 $scope.ScreenListVisible=!$scope.ScreenListVisible;
}
//鼠标移出点击 将图标隐藏
$scope.ShowScreenMoveClick=function(){
  if ($scope.ScreenListVisible) {
   $scope.ShowScreen();
 }
}

$scope.searchmes="请输入搜索的人员姓名";
$scope.searchText="";//搜索框内容
try {
  $scope.searchType=$scope.ApiData.searchType;
} catch(e) {
  $scope.searchType=[];
  console.log(e);
}
// 添加 8-9 的筛选 知识结构选择上用  wang 2017-07-11
try{
  $scope.searchTexts = $scope.ApiData.searchTexts;
}catch(e){
  $scope.searchTexts="";
  console.log(e);
}

$scope.searchType.push(1);

$scope.GetTime=function(){
  $scope.startTime=document.getElementById("startTime").value;
  $scope.endTime=document.getElementById("endTime").value;
}


//1:姓名搜索或拼音简写模糊搜索,2:邮箱搜索,3:手机号搜索,4:按时间段搜索,5:按用户部门搜索,6:按角色搜索、7:按用户组搜索
$scope.AddSearchType=function(TypeIndex){
//类型1 2 3 不可共存
if (TypeIndex==1||TypeIndex==2||TypeIndex==3) {
  for(var i = 1, length1 = 3; i <= length1; i++){
    var isHas=$scope.containsObj($scope.searchType,i);
    if (isHas>-1) {
      $scope.searchType.splice(isHas,1);
    }
  }
}
$scope.searchType.push(TypeIndex);
}

//判断数组中是否包含此元素
$scope.containsObj = function(arr, obj) {  
  try {
   var i = arr.length;  
   while (i--) {  

    if (arr[i] === obj) {  
      return i;  
    }  
  }  
  return -1; 
} catch(e) {
        // statements
        return -1;
      }
    }

//将筛选条件去掉 时间项
$scope.TimeClose=function(){
  $scope.TimeVisible=false;
  $scope.startTime="";
  $scope.endTime="";
  var isHas=$scope.containsObj($scope.searchType,4);
  $scope.searchType.splice(isHas,1);
}
//删除筛选条件
$scope.delScreenList=function(arrt,i){
  arrt.splice(i,1);
}
//添加筛选条件
$scope.ScreenClick=function(ScreenVal){
    $scope.ApiData.ViceStyle= {"width":"100%","height": "100%"};//再次点击。修改第二次样式
    $scope.ApiData.ViceStyletankuangbj={"margin":"0px auto"};
    $scope.ScreenListVisible=false;
    var TypeIndex="";
    switch (ScreenVal) {
      case"uname":
      TypeIndex=1;
      $scope.searchmes="请输入搜索的人员姓名";
      $scope.searchText="";
      break;
      case "time":
      $scope.TimeVisible=true;
      $scope.startTime="";
      $scope.endTime="";
      TypeIndex=4;
      break;
      case "org":
      $scope.ApiData.ViceOrgOpen=true;
      TypeIndex=5;
      break;
      case "role":
      $scope.ApiData.ViceRoleOpen=true;
      TypeIndex=6;
      break;
      case "group":
      $scope.ApiData.ViceGroupOpen=true;
      TypeIndex=7;
      break;
      case "email":
      TypeIndex=2;
      $scope.searchmes="请输入想要搜索人员的邮箱";
      $scope.searchText="";
      break;
      case "phone":
      TypeIndex=3;
      $scope.searchmes="请输入想要搜索人员的联系电话";
      $scope.searchText="";
      break;
    }
    $scope.AddSearchType(TypeIndex);
  }
  /***********************页面筛选业务End*************************************************/


  /***************************复选框业务***********************************************/

  $scope.checkAll = function() {
    $scope.SelectAll=!$scope.SelectAll;
    if($scope.SelectAll)
    {
     $scope.ApiData.UserList = angular.copy($scope.userList);
   }else{
    $scope.ApiData.UserList = [];
  }
};
/*******************************复选框业务结束**************************************/

/*******************************搜索查询**************************************/
$scope.myKeyup = function(e){
  var keycode = window.event?e.keyCode:e.which;
  if(keycode==13){

    $scope.searchBtn();
  } 
};
$scope.searchBtn=function(){
    $scope.selected=false;//查看已选
  $scope.pageIndex=1;
  $scope.userList=[];
  $scope.GetuserList();
}
/**********************************获取人员数据**********************************************/
$scope.pageIndex=1;
$scope.pageSize=15;
$scope.userList=[];

//加载更多显示控制
$scope.listmore=function(){

  if ($scope.pageIndex==$scope.pageCount||$scope.pageCount==0) {
    $scope.listmoreVisible=false;
    return;
  }
  $scope.listmoreVisible=true;
}
$scope.oldValue="";//上一次输入的值
//加载更多单击控制
$scope.listmoreClick=function(){
    //2017-10-11-q
    //在点击更多时，如果此时输入框有值，会按输入内容查询更多，如果没有数据
    //——导致null图会出来，把样式顶飞了
   //如果输入框的值没变，执行分页查询
   if($scope.oldValue==$scope.searchText){
    $scope.pageIndex++;
    $scope.GetuserList();
  //执行查询
}else{
 $scope.oldValue=$scope.searchText;
 $scope.searchBtn();
}  

}
//获取人员方法
$scope.GetuserList=function(){
//  if ($scope.searchText) {
//   $scope.searchText=encodeURI($scope.searchText);
// }
if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
    $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
}
$scope.isloading=true;
if($scope.searchText!=undefined){
    $scope.searchText=$scope.searchText.replace(/\s+/g,"");
}
RS.personnelUser({ pageIndex:$scope.pageIndex, pageSize:$scope.pageSize,searchText:$scope.searchText,searchTexts:$scope.searchTexts,searchType:$scope.searchType,startTime:$scope.startTime,endTime:$scope.endTime,orgList:$scope.ApiData.ViceuserOrgList,roleList:$scope.ApiData.ViceuserRoleList,groupList:$scope.ApiData.ViceuserGroupList,userId:sysUserInfo.getuserinfo().user_ID ,powerLV:$scope.ApiData.powerLV,organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function(user){
  $scope.isloading=false;
  if (user.errorcode=="0") {
    if (!user.datas||user.datas.length<=0) {
     $scope.DataNull=true;
   }else{
     $scope.DataNull=false;
   }

//将获取的用户数据加入到数据组中 注意筛选时清除数据
user.datas.forEach( function(element, index) {
  $scope.userList.push(element);
});
$scope.pageIndex=user.pageIndex;
$scope.pageCount=user.pageCount;
$scope.numCount=user.numCount;
$scope.listmore();

}else if (user.errorcode!="0") {
    //Msg.error("请求数据有误");
  }
}, function callback() {
 $scope.DataNull=false;
 Msg.error("请求数据有误");

});
}
//判断 选择器人员列表数据来源 是从参数获取还是通过后台获取
if ($scope.ApiData.DB&&$scope.ApiData.DB=="1") {
  if ($scope.ApiData.DBdata&&$scope.ApiData.DBdata.length>0) {
   $scope.userList=angular.copy($scope.ApiData.DBdata);
 }else {
   $scope.userList=angular.copy($scope.ApiData.UserList); 
 }

}else {

 $scope.GetuserList();
}

//*****************************************************人员导入**************************************************//

$scope.importExcel = function () {
    
    if($scope.userUploader==undefined){
        Msg.warning("此处无法进行导入，请联系管理员！");
    }else{
        document.getElementById("excelFile").click();
    }
}
var trainupfile = $scope.userUploader;
  try{


    trainupfile.onWhenAddingFileFailed = function (item /*{File|FileLikeObject}*/, filter, options) {     // 选择文件后失败       0
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    trainupfile.onAfterAddingFile = function (fileItem) {  // 选择文件后 （成功）   0          
        console.info('onAfterAddingFile', fileItem);
        if (trainupfile.isUploading) {
            Msg.info("有文件正在上传。。");
            return;
        } else {
            var upfileparam = "?userId=" + sysUserInfo.getuserinfo().user_ID;
            //上传文件路径
            fileItem.url = RS.personBatchSelection(upfileparam);
        }
    };
    trainupfile.onAfterAddingAll = function (addedFileItems) { // 选择文件后添加到队列   1 
        console.info('onAfterAddingAll', addedFileItems);
        if (trainupfile.isUploading) {
            Msg.info("有文件正在上传。。");
            return;
        } else {
            trainupfile.uploadAll();
        }
    };
    // 开始上传
    trainupfile.onBeforeUploadItem = function (item) {    // 2 上传之前一项
        console.info('onBeforeUploadItem', item);
        Msg.info("开始导入。。。");
    };
    trainupfile.onProgressItem = function (fileItem, progress) {   // 3 上传进度
        console.info('onProgressItem', fileItem, progress);
    };
    trainupfile.onProgressAll = function (progress) {      //4 队列进度
        console.info('onProgressAll', progress);
    };
    trainupfile.onSuccessItem = function (fileItem, response, status, headers) {   // 5上传成功
        console.info('onSuccessItem', fileItem, response, status, headers); //fileItem 请求信息 response: 返回值status: 返回状态  headers: 请求头 
        document.getElementById("excelFile").value = "";
        if (response.datas != undefined&&response.datas.length>0) {
            for(var a=0;a<response.datas.length;a++){

              //去重验证
              var find=false;
              for(var b=0;b<$scope.ApiData.UserList.length;b++){
                if(response.datas[a].user_ID==$scope.ApiData.UserList[b].user_ID){
                  find=true;
                  break;
                }
              }
              //不存在重复数据
              if(!find){
                $scope.ApiData.UserList.push(response.datas[a]);
              }
            }
            $scope.listmoreVisible=false;
            $scope.GetCheckList();//调用查看已选
        }
        if (response.errorcode == 0) {
            Msg.success("导入成功！");
        } else {
            Msg.error(response.errormsg);
        }
        trainupfile.isUploading=false;
    };
    trainupfile.onErrorItem = function (fileItem, response, status, headers) {     // 5上传失败
        console.info('onErrorItem', fileItem, response, status, headers);
    };
    trainupfile.onCancelItem = function (fileItem, response, status, headers) {    //5取消上传
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    trainupfile.onCompleteItem = function (fileItem, response, status, headers) {  //6     单文件上传完成
        console.info('onCompleteItem', fileItem, response, status, headers);

    };
    trainupfile.onCompleteAll = function () {  // 6 单文件上传完成或者队列上传完成的时候
        console.info('onCompleteAll');
    };
    /*********************************************文件上传结束**********************************************/
  }catch(e){

  }







},
transclude:true,
replace:true,
templateUrl:"/system/views/personnel/selector/selector_user.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);
/*********************************************************用户列表指令***************************************************************/
PensonSelector.directive('selectexpertmodal',['Msg','sysUserInfo','RequestPopService',function(Msg,sysUserInfo,RS){
  return {
    scope:{
      ApiData:'=apidata'
    },
    link: function($scope, $element, $attrs) {

    $scope.exparams = {
        userid: sysUserInfo.getuserinfo().user_ID,  //登录人id
        orgid: sysUserInfo.getuserinfo().organization_ID, //登录人企业id
        searchTxt: "",    //搜索内容、（知识结构名称或拼音）
        type: 1,    // 管理端查询专家
        pageIndex: 1,   //起始下标
        pageSize: 15 //页数
    }
    $scope.expertList=[];

    $scope.checkAll = function() {
        $scope.SelectAll=!$scope.SelectAll;
        if($scope.SelectAll){
            $scope.ApiData.expertList = angular.copy($scope.expertList);
        }else{
            $scope.ApiData.expertList = [];
        }
    };

    /*******************************搜索查询**************************************/
    $scope.myKeyup = function(e){
      var keycode = window.event?e.keyCode:e.which;
      if(keycode==13){
        $scope.searchBtn();
      } 
    };
    $scope.searchBtn=function(){
          $scope.exparams.pageIndex=1;
          $scope.expertList=[];
          $scope.GetExpertList();
    }
    //加载更多显示控制
    $scope.listmore=function(){
      if ($scope.pageIndex==$scope.pageCount||$scope.pageCount==0) {
        $scope.listmoreVisible=false;
        return;
      }
      $scope.listmoreVisible=true;
    }
    $scope.oldValue="";//上一次输入的值
    //加载更多单击控制
    $scope.listmoreClick=function(){
        //2017-10-11-q
        //在点击更多时，如果此时输入框有值，会按输入内容查询更多，如果没有数据
        //——导致null图会出来，把样式顶飞了
       //如果输入框的值没变，执行分页查询
       if($scope.oldValue==$scope.searchText){
            $scope.exparams.pageIndex++;
            $scope.GetExpertList();
          //执行查询
        }else{
             $scope.oldValue=$scope.exparams.searchText;
             $scope.searchBtn();
        }  
    }
    //获取人员方法
    $scope.GetExpertList=function(){

        $scope.isloading=true;
        if($scope.exparams.searchText!=undefined){
            $scope.exparams.searchText=$scope.exparams.searchText.replace(/\s+/g,"");
        }
        RS.findExpert($scope.exparams).then(function(user){
              $scope.isloading=false;
                  if (user.errorcode=="0") {
                    if (!user.datas||user.datas.length<=0) {
                        $scope.DataNull=true;
                   }else{
                        $scope.DataNull=false;
                   }
                //将获取的用户数据加入到数据组中 注意筛选时清除数据
                user.datas.forEach( function(element, index) {
                  $scope.expertList.push(element);
                });
                $scope.exparams.pageIndex=user.pageIndex;
                $scope.exparams.pageCount=user.pageCount;
                $scope.exparams.numCount=user.numCount;
                $scope.listmore();
            }
        }, function callback() {
             $scope.DataNull=false;
             Msg.error("请求数据有误");
        });
    }
    $scope.GetExpertList();

},
transclude:true,
replace:true,
templateUrl:"/system/views/personnel/selector/selector_expert.html",
    restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
    };
}]);
/*********************************************************组织机构指令*****************************************************************************************/
PensonSelector.directive('selectorgmodal',['sysUserInfo','RequestPopService','Msg',function(sysUserInfo,RS,Msg){
  return {
    scope:{
      ApiData:'=apidata'
    },
    link: function($scope, $element, $attrs) {
      $scope.myKeyup = function(e){
//        var keycode = window.event?e.keyCode:e.which;
//        if(keycode==13){
//          $scope.searchBtn();
//        }
if($scope.searchText==""){
 $scope.GetorgList();
}

};
$scope.searchBtn=function(){
  $scope.GetorgList();
}
$scope.GetorgList=function(){
 $scope.isloading=true;
 $scope.nullObj={organization_ID:"-1",organization_Name:"未分组",wSort:0};
 if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
    $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
}
if($scope.searchText!=undefined){
    $scope.searchText=$scope.searchText.replace(/\s+/g,"");
}
 RS.personnelOrg({searchText:$scope.searchText,orgList:"",userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().orgStr}).then(function(Org){
   $scope.isloading=false;
   if (Org.errorcode=="0") {
    if($scope.ApiData.hasNullOrg){
        Org.datas.push($scope.nullObj);
     }
//将获取的部门数据加入到数据组中 注意筛选时清除数据

$scope.treedataOrg=angular.copy(Org.datas);
//排序
$scope.treedataOrg=$scope.treedataOrg.sort(function(obj1,obj2){
  return obj1.wSort-obj2.wSort;
})
$scope.ApiData.allTreeOrg=$scope.treedataOrg;
$scope.isShowData();
//


if($scope.treedataOrg!=undefined && $scope.treedataOrg!=null){
  $scope.treedataOrg=$scope.treedataOrg.sort(function(obj1,obj2){
    return obj1.wSort-obj2.wSort;
  })
}
$scope.ApiData.allTreeOrg=$scope.treedataOrg;
$scope.isShowData();
//


}else if (Org.errorcode!="0") {

}
//console.log($scope.DataNull);
}, function callback() {
  $scope.DataNull=true;
  Msg.error("请求数据有误");

});
}

$scope.isShowData=function(){

 if (!$scope.ApiData.allTreeOrg||$scope.ApiData.allTreeOrg.length<=0) {
  return true;
}else{

  return false;
}
}
$scope.currentTab="-1";
    //修改选中样式
    $scope.isActiveTab = function (tabUrl) {

     return tabUrl == $scope.currentTab;
   }

//展开或收缩
$scope.showSelectedcollapsedOrg = function (scope,event,haschildren,index) {
  event.stopPropagation();
  scope.toggle();
  if (haschildren<=0) {
    $scope.SelectedModalOrg(scope,event);
    return;
  }
   var nodeData = scope.$modelValue;//获取当前节点对象
   if(nodeData.children==null || nodeData.children.length<=0) //判定是否已经加载此对象子集数据
   { 
    $scope.currentTab = index;
    if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
    RS.personnelOrg({searchText:"",orgList:nodeData,userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().orgStr }).then(function(Org){

      $scope.currentTab="";
      if (Org.errorcode=="0") {
        if (!Org.datas||Org.datas.length<=0) {
          Msg.warning("此节点暂无数据！");
        }else{
         
          nodeData.children=angular.copy(Org.datas);
          
          nodeData.children=nodeData.children.sort(function(obj1,obj2){
            return obj1.wSort-obj2.wSort;
          });
          $scope.DataNull=false;
        }
      }else if (Org.errorcode!="0") {
      }
    }, function callback() {
         // $scope.DataNull=false;
         Msg.error("请求数据有误！");

         
       });
  }
};

$scope.containsOrg = function(arr, obj) {  
  try {
    var i = arr.length;  
    while (i--) {
      if (arr[i].organization_ID === obj.organization_ID) {  
        return i;  
      }
    }
    return -1; 
  } catch(e) {
        // statements
        return -1;
      }
    }

    $scope.containsOrgValues = function(arr, obj) {  
      try {
        var i = arr.length;  
        while (i--) {
          if (arr[i].organization_ID === obj) {  
            return i;  
          }
        }
        return -1; 
      } catch(e) {
        // statements
        return -1;
      }
    }
//选中触发方法
$scope.SelectedModalOrg=function(scope,event){
  event.stopPropagation();
  if ($scope.ApiData.ViceOrgOpen) {
        //判断是否已选中次对象
        var result=$scope.containsOrg($scope.ApiData.ViceuserOrgList,scope.$modelValue);
        if (result>-1) {//已选中的话 取消选中
          $scope.ApiData.ViceuserOrgList.splice(result,1);
        }else {//未选中 进行选中操作
          $scope.ApiData.ViceuserOrgList.push(scope.$modelValue);
        }

        var result2=$scope.containsOrgValues($scope.ApiData.userOrgValues,scope.$modelValue.organization_ID);
        if (result2>-1) {//已选中的话 取消选中            
          $scope.ApiData.userOrgValues.splice(result2,1);
        }else {//未选中 进行选中操作
          if($scope.ApiData.userOrgValues!=undefined){
            $scope.ApiData.userOrgValues.push({organization_ID:scope.$modelValue.organization_ID ,boss:false});
          }
        }

      }else {
        //判断是否已选中次对象
        var result=$scope.containsOrg($scope.ApiData.userOrgList,scope.$modelValue);
        if (result>-1) {//已选中的话 取消选中
          $scope.ApiData.userOrgList.splice(result,1);            
        }else {//未选中 进行选中操作
          $scope.ApiData.userOrgList.push(scope.$modelValue);
        }

        var result2=$scope.containsOrgValues($scope.ApiData.userOrgValues,scope.$modelValue.organization_ID);
        if (result2>-1) {//已选中的话 取消选中            
          $scope.ApiData.userOrgValues.splice(result2,1);
        }else {//未选中 进行选中操作
          if($scope.ApiData.userOrgValues!=undefined){
            $scope.ApiData.userOrgValues.push( {organization_ID:scope.$modelValue.organization_ID ,boss:false});
          }
        }
      }
    }

//选中样式判断
$scope.IscheckModalOrg=function(scope){
 if ($scope.ApiData.ViceOrgOpen) {
   var result=$scope.containsOrg($scope.ApiData.ViceuserOrgList,scope.$modelValue);
   return result>-1;
 }else {
  var result=$scope.containsOrg($scope.ApiData.userOrgList,scope.$modelValue);
  return result>-1;
}

}


var guid = new GUID();
$scope.SpeeOrgObj="";
$scope.SpeeName="";
//新增部门
$scope.AddSpeedOrg=function(scope,event,NodeOrg) {
  $scope.SpeeOrgObj=NodeOrg;
  $scope.speedCreate=true;
  event.stopPropagation();

}
$scope.CloseSpeedOrg=function(scope,event) {
  $scope.speedCreate=false;
  event.stopPropagation();
  
}



//保存
$scope.SaveSpeedOrg=function (NodeOrg) {
//部门对象
$scope.PublicObj = {
  organization_ID: "",
  organization_Name:$scope.SpeeName,
  parentId: NodeOrg.organization_ID,
  parentName: NodeOrg.organization_Name,
  organization_Num: 0,
  wSort: 1,
  wSortLayer: NodeOrg.wSortLayer + "-" + guid.newGUID(),
  organization_No: "",
  organization_InnerPhone: "",
  organization_OuterPhone: "",
  organization_Phone: "",
  createUserId: sysUserInfo.getuserinfo().user_ID,
  createUserName: sysUserInfo.getuserinfo().username,
  userrole: sysUserInfo.getuserinfo().powerLV
};


if ($scope.PublicObj.organization_Name == undefined || $scope.PublicObj.organization_Name.length == 0) { Msg.warning('组织机构名称不能为空！'); return; }
if ($scope.PublicObj.organization_ID == "" && $scope.PublicObj.parentId == "0") {
  $scope.PublicObj.wSortLayer = guid.newGUID();
} else if ($scope.PublicObj.organization_ID == "" && $scope.PublicObj.parentId != "0") {
  $scope.PublicObj.wSortLayer = $scope.PublicObj.wSortLayer + "-" + guid.newGUID();
} else if ($scope.PublicObj.organization_ID != "" && $scope.PublicObj.parentId == "0") {
            //$scope.PublicObj.wSortLayer = guid.newGUID();
          } else {

          }

          RS.AddEditOrg({ data: $scope.PublicObj, addPeopleList:[], delPeopleList:[], addPersonList: [], delPersonList: [], organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (data) {
            $scope.isloading = false;
            $scope.addPersonList = [];
            $scope.delPersonList = [];
            if (data.errorcode == "0") {
              if (!$scope.PublicObj.organization_ID) {
                Msg.success("新增成功！");
                $scope.PublicObj.organization_ID = data.id;
                $scope.PublicObj.haschildren = 0;

              } 
              $scope.ArrayRecursion($scope.treedataOrg, $scope.PublicObj, "", 1);
            }
          }, function callback() {
            Msg.error("请求数据有误");

          });

          $scope.speedCreate=false;
        }
        $scope.SetChildNode = function (id, newnum) {
          RS.SetChildNode({ id: id, optype: 1, newnum: newnum }).then(function (Data) {
            if (Data.errorcode != "0") {
              Msg.error("节点子集添加失败");
            }
          }, function callback() {
            Msg.error("节点子集请求数据有误");
          });
        }
        $scope.ArrayRecursion = function (DataArray, childObj, parentId, fun) {
          if (fun == 1) {
            DataArray.forEach(function (element, index) {
              if (element.organization_ID == childObj.parentId) {
                element.haschildren++;
                $scope.SetChildNode(element.organization_ID, element.haschildren);
                if (element.children) {
                  element.children.push(childObj);
                } else {
          // element.children = [];
          // element.children.push(childObj);
        }
      } else {
        if (element.children) {
          $scope.ArrayRecursion(element.children, childObj, "", 1);
        }
      }
    });
            if (DataArray.length <= 0) {
              if (childObj != undefined || childObj != null || childObj != "")
                DataArray.push(childObj);
            }
          } 
        }





        $scope.GetorgList();
      },

      replace:true,
      templateUrl:"/system/views/personnel/selector/selector_org.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);
//组织机构指令 独立弹出
PensonSelector.directive('selectorgmodalhtml',[function(){
  return {
    link: function($scope, $element, $attrs) {

    },
    replace:true,
    templateUrl:"/system/views/personnel/selector/selector_orghtml.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);
/*********************************************************用户组指令*****************************************************************************************/
PensonSelector.directive('selectgroupmodal',['sysUserInfo','RequestPopService','Msg',function(sysUserInfo,RS,Msg){
  return {
    scope:{
      ApiData:'=apidata'
    },
    link: function($scope, $element, $attrs) {

     $scope.myKeyup = function(e){
//      var keycode = window.event?e.keyCode:e.which;
//      if(keycode==13){
//        $scope.searchBtn();
//      }
if($scope.searchText==""){
 $scope.GetgroupList();
} 
};
$scope.searchBtn=function(){
  $scope.GetgroupList();
}

$scope.GetgroupList=function(){
  $scope.isloading=true;
  if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
    if($scope.searchText!=undefined){
        $scope.searchText=$scope.searchText.replace(/\s+/g,"");
    }
  RS.personnelGroup({searchText:$scope.searchText,groupList:"",userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().groupStr }).then(function(Group){
   $scope.isloading=false;
   if (Group.errorcode=="0") {


    $scope.treedataGroup=angular.copy(Group.datas);

//将获取的部门数据加入到数据组中 注意筛选时清除数据

//排序
$scope.treedataGroup=$scope.treedataGroup.sort(function(obj1,obj2){
  return obj1.wSort-obj2.wSort;
});
$scope.ApiData.allTreeOrg=$scope.treedataGroup;
$scope.isShowData();
}else if (Group.errorcode!="0") {
}
}, function callback() {
  $scope.DataNull=false;
  Msg.error("请求数据有误");
  

});
}
$scope.isShowData=function(){

 if (!$scope.ApiData.allTreeOrg||$scope.ApiData.allTreeOrg.length<=0) {
  return true;
}else{

  return false;
}
}

$scope.currentTab="-1";
    //修改选中样式
    $scope.isActiveTab = function (tabUrl) {

     return tabUrl == $scope.currentTab;
   }

//展开或收缩
$scope.showSelectedcollapsedGroup = function (scope,event,haschildren,index) {
  event.stopPropagation();
  scope.toggle();

  if (haschildren<=0) {
    $scope.SelectedModalGroup(scope,event);
    return;
  }
   var nodeData = scope.$modelValue;//获取当前节点对象

   if (!nodeData.children) {
    nodeData.children=[];
  }
//  ||nodeData.children.length<nodeData.haschildren
   if(nodeData.children==null || nodeData.children.length<=0) //判定是否已经加载此对象子集数据
   {  
     $scope.currentTab = index;
       if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
     RS.personnelGroup({searchText:"",groupList:nodeData,userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().groupStr }).then(function(Group){
      $scope.currentTab="";
      if (Group.errorcode=="0") {
        if (!Group.datas||Group.datas.length<=0) {
         Msg.warning("此节点暂无数据！");
       }else{
         $scope.DataNull=false;
       }
       nodeData.children=angular.copy(Group.datas);
            //排序
            nodeData.children=nodeData.children.sort(function(obj1,obj2){
              return obj1.wSort-obj2.wSort;
            }) 
          }else if (Group.errorcode!="0") {
          }
        }, function callback() {
          $scope.DataNull=false;
          Msg.error("请求数据有误");


        });
   }
 };
 $scope.containsGroup = function(arr, obj) {  
  try {
    var i = arr.length;  
    while (i--) {  
      if (arr[i].userGroup_ID === obj.userGroup_ID) {  
        return i;  
      }
    }  
    return -1; 
  } catch(e) {
        // statements
        return -1;
      }
    }
    
    $scope.containsGroupValues = function(arr, obj) {  
      try {
        var i = arr.length;  
        while (i--) {
          if (arr[i].userGroup_ID === obj) {  
            return i;  
          }
        }
        return -1; 
      } catch(e) {
        // statements
        return -1;
      }
    }
//选中触发方法
$scope.SelectedModalGroup=function(scope,event){
  event.stopPropagation();
//判断是否第二次进入
if($scope.ApiData.ViceGroupOpen)
{
 var result=$scope.containsGroup($scope.ApiData.ViceuserGroupList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.ViceuserGroupList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.ViceuserGroupList.push(scope.$modelValue);
    }

    var result2=$scope.containsGroupValues($scope.ApiData.userGroupValues,scope.$modelValue.userGroup_ID);
        if (result2>-1) {//已选中的话 取消选中            
          $scope.ApiData.userGroupValues.splice(result2,1);
        }else {//未选中 进行选中操作
          $scope.ApiData.userGroupValues.push({userGroup_ID:scope.$modelValue.userGroup_ID ,boss:false});
        }

      }
      else
      {
    //判断是否已选中次对象
    var result=$scope.containsGroup($scope.ApiData.userGroupList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.userGroupList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.userGroupList.push(scope.$modelValue);
    }

    var result2=$scope.containsGroupValues($scope.ApiData.userGroupValues,scope.$modelValue.userGroup_ID);
        if (result2>-1) {//已选中的话 取消选中            
          $scope.ApiData.userGroupValues.splice(result2,1);
        }else {//未选中 进行选中操作
          if($scope.ApiData.userGroupValues!=undefined){
            $scope.ApiData.userGroupValues.push({userGroup_ID:scope.$modelValue.userGroup_ID ,boss:false});
          }
        }
      }
    }
//选中样式判断
$scope.IscheckModalGroup=function(scope){

  if ($scope.ApiData.ViceGroupOpen) {
   var result=$scope.containsGroup($scope.ApiData.ViceuserGroupList,scope.$modelValue);
   return result>-1;
 }else {
   var result=$scope.containsGroup($scope.ApiData.userGroupList,scope.$modelValue);
   return result>-1;
 }
}


 var guid = new GUID();
 $scope.SpeeGroupObj="";
 $scope.SpeeName="";
//新增用户组
$scope.AddSpeedGroup=function(scope,event,NodeGroup) {
  $scope.SpeeGroupObj=NodeGroup;
  $scope.speedCreate=true;
  event.stopPropagation();
  
}
$scope.CloseSpeedGroup=function(scope,event) {
  $scope.speedCreate=false;
  event.stopPropagation();
  
}



//保存
$scope.SaveSpeedGroup=function (NodeGroup) {
//角色对象
$scope.PublicObj = {
  userGroup_ID: "",
  userGroup_Name:$scope.SpeeName,
  parentId: NodeGroup.userGroup_ID,
  parentName: NodeGroup.userGroup_Name,
  userGroup_Num: 0,
  wSortLayer: NodeGroup.wSortLayer + "-" + guid.newGUID(),
  wSort: 1,
  userGroup_No:guid.newGUID(),
  createUserId: sysUserInfo.getuserinfo().user_ID,
  createUserName: sysUserInfo.getuserinfo().username,
  organization_ID: sysUserInfo.getuserinfo().organization_ID
};


if ($scope.PublicObj.userGroup_Name == undefined || $scope.PublicObj.userGroup_Name.length == 0) { Msg.warning('节点名称不能为空！'); return; }
if ($scope.PublicObj.userGroup_ID == "" && $scope.PublicObj.parentId == "0") {
  $scope.PublicObj.wSortLayer = guid.newGUID();
} else if ($scope.PublicObj.userGroup_ID == "" && $scope.PublicObj.parentId != "0") {
  $scope.PublicObj.wSortLayer = $scope.PublicObj.wSortLayer + "-" + guid.newGUID();
} else if ($scope.PublicObj.userGroup_ID != "" && $scope.PublicObj.parentId == "0") {
           // $scope.PublicObj.wSortLayer = guid.newGUID();
         } else {
           
         }

         RS.AddEditGroup({ data: $scope.PublicObj, addPeopleList: [], delPeopleList:[], addPersonList:[], delPersonList: [], authority_ID: "", authority:[], organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (data) {
          if (data.errorcode == "0") {
            if (!$scope.PublicObj.userGroup_ID) {
              Msg.success("新增成功");
              $scope.PublicObj.userGroup_ID = data.id;
              $scope.PublicObj.haschildren = 0;
            } 
            $scope.ArrayRecursion($scope.treedataGroup, $scope.PublicObj, "", 1);
            
          } else {
            Msg.error("操作失败");
          }
        }, function callback() {
          Msg.error("请求数据有误");

        });

         $scope.speedCreate=false;
       }
       $scope.SetChildNode = function (id, newnum) {
        RS.SetChildNode({ id: id, optype: 3, newnum: newnum }).then(function (Data) {
          if (Data.errorcode != "0") {
            Msg.error("节点子集添加失败");
          }
        }, function callback() {
          Msg.error("节点子集请求数据有误");
        });
      }
    //递归修改 DataArray:数据集合 childObj:对象 parentId: 父集id fun :执行方法 1 新增 2删除
    $scope.ArrayRecursion = function (DataArray, childObj, parentId, fun) {
      if (fun == 1) {
        if (childObj.parentId == "0") {
          try {
            DataArray.push(childObj);
          } catch (e) {
            DataArray = [];
            DataArray.push(childObj);
          }

        } else {
          DataArray.forEach(function (element, index) {
            if (element.userGroup_ID == childObj.parentId) {
              element.haschildren++;
              $scope.SetChildNode(element.userGroup_ID, element.haschildren);
              if (element.children) {
                element.children.push(childObj);
              } else {
                            // element.children = [];
                            // element.children.push(childObj);
                          }
                        } else {
                          if (element.children) {
                            $scope.ArrayRecursion(element.children, childObj, "", 1);
                          }
                        }
                      });
        }
      } 
    }
$scope.GetgroupList();
},
replace:true,
templateUrl:"/system/views/personnel/selector/selector_group.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);

PensonSelector.directive('selectgroupmodalhtml',[function(){
  return {
    link: function($scope, $element, $attrs) {

    },
    replace:true,
    templateUrl:"/system/views/personnel/selector/selector_grouphtml.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);

//****************************************************角色指令**********************************//
PensonSelector.directive('selectrolemodal',['sysUserInfo','RequestPopService','Msg',function(sysUserInfo,RS,Msg){
  return {
    scope:{
      ApiData:'=apidata'
    },
    link: function($scope, $element, $attrs) {
      $scope.myKeyup = function(e){
//        var keycode = window.event?e.keyCode:e.which;
//        if(keycode==13){
//          $scope.searchBtn();
//        }
if($scope.searchText==""){
 $scope.GetgroupList();
} 
};
$scope.searchBtn=function(){
  $scope.GetroleList();
}

$scope.GetroleList=function(){
//        if ($scope.searchText) {
//         $scope.searchText=encodeURI($scope.searchText);
//       }
$scope.isloading=true;
 if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
    if($scope.searchText!=undefined){
    $scope.searchText=$scope.searchText.replace(/\s+/g,"");
    }
RS.personnelRole({searchText:$scope.searchText,roleList:"",userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().roleStr }).then(function(Role){
 $scope.isloading=false;
 if (Role.errorcode=="0") {

  $scope.treedataRole=angular.copy(Role.datas);
//排序

$scope.treedataRole=$scope.treedataRole.sort(function(obj1,obj2){
  return obj1.wSort-obj2.wSort;
})
$scope.ApiData.allTreeOrg=$scope.treedataRole;

$scope.isShowData();
}else if (Role.errorcode!="0") {
}
}, function callback() {
  $scope.DataNull=false;
  Msg.error("请求数据有误");
  

});
}
$scope.isShowData=function(){

 if (!$scope.ApiData.allTreeOrg||$scope.ApiData.allTreeOrg.length<=0) {
  return true;
}else{

  return false;
}
}
$scope.currentTab="-1";
    //修改选中样式
    $scope.isActiveTab = function (tabUrl) {

     return tabUrl == $scope.currentTab;
   }

//展开或收缩
$scope.showSelectedcollapsedRole =function(scope,event,haschildren,index) {
  event.stopPropagation();
  scope.toggle();
  
  if (haschildren<=0) {
    $scope.SelectedModalRole(scope,event);
    return;
  }
   var nodeData = scope.$modelValue;//获取当前节点对象

   if (!nodeData.children) {
    nodeData.children=[];
  }
//  console.log(nodeData);
    if(nodeData.children==null || nodeData.children.length<=0) //判定是否已经加载此对象子集数据
    {
      $scope.currentTab = index;
       if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
      RS.personnelRole({searchText:"",roleList:nodeData,userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().roleStr }).then(function(Role){
        $scope.currentTab="";
        if (Role.errorcode=="0") {
          if (!Role.datas||Role.datas.length<=0) {
            Msg.warning("此节点暂无数据！");
          }else{
           $scope.DataNull=false;
         }
         nodeData.children=angular.copy(Role.datas);
            //排序
            nodeData.children=nodeData.children.sort(function(obj1,obj2){
              return obj1.wSort-obj2.wSort;
            }) 
          }else if (Role.errorcode!="0") {
          }
        }, function callback() {
          $scope.DataNull=false;
          Msg.error("请求数据有误");


        });
    }
  };
  $scope.containsRole = function(arr, obj) {  
    try {
     var i = arr.length;  
     while (i--) {  

      if (arr[i].roles_ID === obj.roles_ID) {  
        return i;  
      }  
    }  
    return -1; 
  } catch(e) {
        // statements
        return -1;
      }
    }

    
    $scope.containsRoleValues = function(arr, obj) {  
      try {
        var i = arr.length;  
        while (i--) {
          if (arr[i].roles_ID === obj) {  
            return i;  
          }
        }
        return -1; 
      } catch(e) {
        // statements
        return -1;
      }
    }

//选中触发方法
$scope.SelectedModalRole=function(scope,event){
  event.stopPropagation();
  if ($scope.ApiData.ViceRoleOpen) {
       //判断是否已选中次对象
       var result=$scope.containsRole($scope.ApiData.ViceuserRoleList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.ViceuserRoleList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.ViceuserRoleList.push(scope.$modelValue);
    }

    var result2=$scope.containsRoleValues($scope.ApiData.userRightValues,scope.$modelValue.roles_ID);
        if (result2>-1) {//已选中的话 取消选中            
          $scope.ApiData.userRightValues.splice(result2,1);
        }else {//未选中 进行选中操作
          $scope.ApiData.userRightValues.push({roles_ID:scope.$modelValue.roles_ID ,boss:false});
        }

      }else {
         //判断是否已选中次对象
         var result=$scope.containsRole($scope.ApiData.userRoleList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.userRoleList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.userRoleList.push(scope.$modelValue);
    }

    var result2=$scope.containsRoleValues($scope.ApiData.userRightValues,scope.$modelValue.roles_ID);
        if (result2>-1) {//已选中的话 取消选中            
          $scope.ApiData.userRightValues.splice(result2,1);
        }else {//未选中 进行选中操作
          if($scope.ApiData.userRightValues!=undefined){
            $scope.ApiData.userRightValues.push({roles_ID:scope.$modelValue.roles_ID ,boss:false});
          }
        }
      }

    }
//选中样式判断
$scope.IscheckModalRole=function(scope){
 if ($scope.ApiData.ViceRoleOpen) {
   var result=$scope.containsRole($scope.ApiData.ViceuserRoleList,scope.$modelValue);
   return result>-1;
 }else {
  var result=$scope.containsRole($scope.ApiData.userRoleList,scope.$modelValue);
  return result>-1;
}
}


var guid = new GUID();
$scope.SpeeRoleObj="";
$scope.SpeeName="";
//新增角色
$scope.AddSpeedRole=function(scope,event,NodeRole) {
  $scope.SpeeRoleObj=NodeRole;
  $scope.speedCreate=true;
  event.stopPropagation();

}
$scope.CloseSpeedRole=function(scope,event) {
  $scope.speedCreate=false;
  event.stopPropagation();
  
}



//保存
$scope.SaveSpeedRole=function (NodeRole) {
//角色对象
$scope.PublicObj = {
  roles_ID: "",
  roles_Name: $scope.SpeeName,
  parentId: NodeRole.roles_ID,
  parentName: NodeRole.roles_Name,
  roles_Num: 0,
  wSort: 1,
  wSortLayer: NodeRole.wSortLayer + "-" + guid.newGUID(),
  roles_No: guid.newGUID(),
  createUserId: sysUserInfo.getuserinfo().user_ID,
  createUserName: sysUserInfo.getuserinfo().username,
  organization_ID: sysUserInfo.getuserinfo().organization_ID
};


if ($scope.PublicObj.roles_Name == undefined || $scope.PublicObj.roles_Name.length == 0) { Msg.warning('节点名称不能为空！'); return; }
if ($scope.PublicObj.roles_ID == "" && $scope.PublicObj.parentId == "0") {
  $scope.PublicObj.wSortLayer = guid.newGUID();
} else if ($scope.PublicObj.roles_ID == "" && $scope.PublicObj.parentId != "0") {
  $scope.PublicObj.wSortLayer = $scope.PublicObj.wSortLayer + "-" + guid.newGUID();
} else if ($scope.PublicObj.roles_ID != "" && $scope.PublicObj.parentId == "0") {
            //$scope.PublicObj.wSortLayer = guid.newGUID();
          } else {
            /*
            if ($scope.PublicObj.wSortLayer.lastIndexOf("-") >= 0) {
            $scope.PublicObj.wSortLayer = $scope.PublicObj.wSortLayer.substring(0, $scope.PublicObj.wSortLayer.lastIndexOf("-")) + "-" + guid.newGUID();
            } else {
            $scope.PublicObj.wSortLayer = $scope.PublicObj.wSortLayer + "-" + guid.newGUID();
            }
            */
          }

          RS.AddEditRole({ data: $scope.PublicObj, addPeopleList: [], delPeopleList: [], addPersonList:[], delPersonList: [], authority_ID:"", authority: [], organization_ID: sysUserInfo.getuserinfo().organization_ID }).then(function (data) {

            if (data.errorcode == "0") {
              if (!$scope.PublicObj.roles_ID) {
                Msg.success("新增成功");
                $scope.PublicObj.roles_ID = data.id;
                $scope.PublicObj.haschildren = 0;
                    // 如果是负责人的那么添加后再给本地添加信息
                    if (sysUserInfo.getuserinfo().powerLV == "3") {
                      if (!sysUserInfo.getuserinfo().hasOwnProperty("userRoleList"))
                        sysUserInfo.getuserinfo().userRoleList = [];
                      $scope.olduserinfo = sysUserInfo.getuserinfo();
                      $scope.PublicObj.boss = true;
                      $scope.olduserinfo.userRoleList.push($scope.PublicObj);
                        // 添加设置负责人的部门
                        sysUserInfo.setuserinfo($scope.olduserinfo);
                      }
                    } 
                    $scope.ArrayRecursion($scope.treedataRole, $scope.PublicObj, "", 1);

                  } else {
                    Msg.error("操作失败");
                  }
                }, function callback() {
                  Msg.error("请求数据有误");

                });

          $scope.speedCreate=false;
        }
        $scope.SetChildNode = function (id, newnum) {
          RS.SetChildNode({ id: id, optype: 2, newnum: newnum }).then(function (Data) {
            if (Data.errorcode != "0") {
              Msg.error("节点子集添加失败");
            }
          }, function callback() {
            Msg.error("节点子集请求数据有误");
          });
        }
    //递归修改 DataArray:数据集合 childObj:对象 parentId: 父集id fun :执行方法 1 新增 2删除
    $scope.ArrayRecursion = function (DataArray, childObj, parentId, fun) {
      if (fun == 1) {
        if (childObj.parentId == "0") {
          DataArray.push(childObj);
        } else {
          DataArray.forEach(function (element, index) {
            if (element.roles_ID == childObj.parentId) {
              element.haschildren++;
              $scope.SetChildNode(element.roles_ID, element.haschildren);
              if (element.children) {
                element.children.push(childObj);
              } else {
                            // element.children = [];
                            // element.children.push(childObj);
                          }
                        } else {
                          if (element.children) {
                            $scope.ArrayRecursion(element.children, childObj, "", 1);
                          }
                        }
                      });
        }
      } 
    }





    $scope.GetroleList();
  },
  replace:true,
  templateUrl:"/system/views/personnel/selector/selector_role.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);

PensonSelector.directive('selectrolemodalhtml',[function(){
  return {
    link: function($scope, $element, $attrs) {

    },
    replace:true,
    templateUrl:"/system/views/personnel/selector/selector_rolehtml.html",
        restrict: 'EC', // E = Element, A = Attribute, C = Class, M = Comment
      };
    }]);


//**********************************************************部门选择器*************************************//
PensonSelector.controller('PensonSelectorOrgCtrl', ['$scope','Msg','sysUserInfo','RequestPopService',
  function($scope,Msg,sysUserInfo,RS){
   $scope.myKeyup = function(e){
    var keycode = window.event?e.keyCode:e.which;
    if(keycode==13){
      $scope.searchOrgBtn();
    } 

  };
  $scope.searchOrgText="";
  $scope.loadShowMe=true;
  $scope.searchOrgBtn=function(){
    $scope.GetorgList();
  }

  $scope.GetorgList=function(){
//    if ($scope.searchText) {
//     $scope.searchText=encodeURI($scope.searchText);
//   }

$scope.isloading=true;
  if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
    if($scope.searchOrgText!=undefined){
    $scope.searchOrgText=$scope.searchOrgText.replace(/\s+/g,"");
    }
RS.personnelOrg({searchText:$scope.searchOrgText,orgList:"",userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().orgStr}).then(function(Org){
  $scope.isloading=false;
  if (Org.errorcode=="0"&&Org.datas!=undefined) {
    
    $scope.treedataOrg=angular.copy(Org.datas);
//排序
$scope.treedataOrg=$scope.treedataOrg.sort(function(obj1,obj2){
  return obj1.wSort-obj2.wSort;
})
$scope.ApiData.allTreeOrg=$scope.treedataOrg;
$scope.isShowData();
}else if (Org.errorcode!="0") {

}
}, function callback() {
  $scope.DataNull=false;
  Msg.error("请求数据有误");

});
}
$scope.isShowData=function(){

 if (!$scope.ApiData.allTreeOrg||$scope.ApiData.allTreeOrg.length<=0) {
  return true;
}else{

  return false;
}
}
$scope.currentTab="-1";
    //修改选中样式
    $scope.isActiveTab = function (tabUrl) {
     return tabUrl == $scope.currentTab;
   }

//展开或收缩
$scope.showSelectedcollapsedOrg =function (scope,event,haschildren,index) {
  event.stopPropagation();

  scope.toggle();

  if (haschildren<=0) {
    $scope.SelectedModalOrg(scope,event);
    return;
  }

   var nodeData = scope.$modelValue;//获取当前节点对象

   if(nodeData.children==null|| nodeData.children.length<=0) //判定是否已经加载此对象子集数据
   { 
   if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
     $scope.currentTab = index;
     RS.personnelOrg({searchText:"",orgList:nodeData,userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().orgStr }).then(function(Org){
      $scope.currentTab="";
      if (Org.errorcode=="0"&&Org.datas!=undefined) {
        if (!Org.datas||Org.datas.length<=0) {
         Msg.warning("此节点暂无数据！");
       }else{
         $scope.DataNull=false;
       }
       nodeData.children=angular.copy(Org.datas);
            //排序
            nodeData.children=nodeData.children.sort(function(obj1,obj2){
              return obj1.wSort-obj2.wSort;
            }) 
          }else if (Org.errorcode!="0") {
          }
        }, function callback() {
          $scope.DataNull=false;
          Msg.error("请求数据有误");


        });
   }
 };

 $scope.containsOrg = function(arr, obj) {  
  try {
    var i = arr.length;  
    while (i--) {
      if (arr[i].organization_ID === obj.organization_ID) {  
        return i;  
      }
    }
    return -1; 
  } catch(e) {
        // statements
        return -1;
      }
    }

    $scope.containsOrgValues = function(arr, obj) {  
      try {
        var i = arr.length;  
        while (i--) {
          if (arr[i].organization_ID === obj) {  
            return i;  
          }
        }
        return -1; 
      } catch(e) {
        // statements
        return -1;
      }
    }
//选中触发方法
$scope.SelectedModalOrg=function(scope,event){

  //scope=angurlar.element(scope).parent();
  event.stopPropagation();

  if ($scope.ApiData.ViceOrgOpen) {
         //判断是否已选中次对象
         var result=$scope.containsOrg($scope.ApiData.ViceuserOrgList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.ViceuserOrgList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.ViceuserOrgList.push(scope.$modelValue);
    }
  }
  else {
          //判断是否已选中次对象
          var result=$scope.containsOrg($scope.ApiData.userOrgList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.userOrgList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.userOrgList.push(scope.$modelValue);
    }   
  }

}
//选中样式判断
$scope.IscheckModalOrg=function(scope){
 if ($scope.ApiData.ViceOrgOpen) {
   var result=$scope.containsOrg($scope.ApiData.ViceuserOrgList,scope.$modelValue);
   return result>-1;
 }else {
  var result=$scope.containsOrg($scope.ApiData.userOrgList,scope.$modelValue);
  return result>-1;
}

}
$scope.GetorgList();
}]);

//**********************************************************用户组选择器*******************************************//

PensonSelector.controller('PensonSelectorGroupCtrl', ['$scope','Msg','sysUserInfo','RequestPopService',
  function($scope,Msg,sysUserInfo,RS){
   $scope.myKeyup = function(e){
    var keycode = window.event?e.keyCode:e.which;
    if(keycode==13){
      $scope.searchGroupBtn();
    } 
  };
  $scope.searchGroupBtn=function(){
    $scope.GetgroupList();
  }
  $scope.searchGroupText="";
  $scope.GetgroupList=function(){
//    if ($scope.searchText) {
//     $scope.searchText=encodeURI($scope.searchText);
//   }
$scope.isloading=true;
if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
     if($scope.searchGroupText!=undefined){
    $scope.searchGroupText=$scope.searchGroupText.replace(/\s+/g,"");
    }
RS.personnelGroup({searchText:$scope.searchGroupText,groupList:"",userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().groupStr }).then(function(Group){
 $scope.isloading=false;
 if (Group.errorcode=="0"&&Group.datas!=undefined) {
//将获取的部门数据加入到数据组中 注意筛选时清除数据

$scope.treedataGroup=angular.copy(Group.datas);
//排序
$scope.treedataGroup=$scope.treedataGroup.sort(function(obj1,obj2){
  return obj1.wSort-obj2.wSort;
})
$scope.ApiData.allTreeOrg=$scope.treedataGroup;
$scope.isShowData();
}else if (Group.errorcode!="0") {
}
}, function callback() {
  $scope.DataNull=false;
  Msg.error("请求数据有误");

});
}
$scope.isShowData=function(){

 if (!$scope.ApiData.allTreeOrg||$scope.ApiData.allTreeOrg.length<=0) {
  return true;
}else{

  return false;
}
}
$scope.currentTab="-1";
    //修改选中样式
    $scope.isActiveTab = function (tabUrl) {

     return tabUrl == $scope.currentTab;
   }
//展开或收缩
$scope.showSelectedcollapsedGroup = function (scope,event,haschildren,index) {
  event.stopPropagation();
  scope.toggle();
  if (haschildren<=0) {
    $scope.SelectedModalGroup(scope,event);
    return;
  }
   var nodeData = scope.$modelValue;//获取当前节点对象
   if (!nodeData.children) {
    nodeData.children=[];
  }
//  ||nodeData.children.length<nodeData.haschildren
   if(nodeData.children== null|| nodeData.children.length<=0) //判定是否已经加载此对象子集数据
     {  $scope.currentTab = index;
     if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
       RS.personnelGroup({searchText:"",groupList:nodeData,userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().groupStr }).then(function(Group){
         $scope.currentTab="";
         if (Group.errorcode=="0") {
          if (!Group.datas||Group.datas.length<=0) {
            Msg.warning("此节点暂无数据！");
          }else{
           $scope.DataNull=false;
         }
         nodeData.children=angular.copy(Group.datas);
            //排序
            nodeData.children=nodeData.children.sort(function(obj1,obj2){
              return obj1.wSort-obj2.wSort;
            }) 
          }else if (Group.errorcode!="0") {
          }
        }, function callback() {
          $scope.DataNull=false;
          Msg.error("请求数据有误");


        });
     }
   };

   $scope.containsGroup = function(arr, obj) {  
    try {
      var i = arr.length;  
      while (i--) {  
        if (arr[i].userGroup_ID === obj.userGroup_ID) {  
          return i;  
        }
      }  
      return -1; 
    } catch(e) {
        // statements
        return -1;
      }
    }
    
    $scope.containsGroupValues = function(arr, obj) {  
      try {
        var i = arr.length;  
        while (i--) {
          if (arr[i].userGroup_ID === obj) {  
            return i;  
          }
        }
        return -1; 
      } catch(e) {
        // statements
        return -1;
      }
    }

//选中触发方法
$scope.SelectedModalGroup=function(scope,event){
  event.stopPropagation();
//判断是否第二次进入
if($scope.ApiData.ViceGroupOpen)
{
 var result=$scope.containsGroup($scope.ApiData.ViceuserGroupList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.ViceuserGroupList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.ViceuserGroupList.push(scope.$modelValue);
    }
  }
  else
  {
    //判断是否已选中次对象
    var result=$scope.containsGroup($scope.ApiData.userGroupList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.userGroupList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.userGroupList.push(scope.$modelValue);
    }
  }
}
//选中样式判断
$scope.IscheckModalGroup=function(scope){

  if ($scope.ApiData.ViceGroupOpen) {
   var result=$scope.containsGroup($scope.ApiData.ViceuserGroupList,scope.$modelValue);
   return result>-1;
 }else {
   var result=$scope.containsGroup($scope.ApiData.userGroupList,scope.$modelValue);
   return result>-1;
 }

}
$scope.GetgroupList();

}]);
    //角色控制器 
PensonSelector.controller('PensonSelectorRoleCtrl', ['$scope','Msg','sysUserInfo','RequestPopService',
      function($scope,Msg,sysUserInfo,RS){

//*************************************************角色选择器************************************************//
$scope.myKeyup = function(e){
  var keycode = window.event?e.keyCode:e.which;
  if(keycode==13){
    $scope.searchRoleBtn();
  } 
};
$scope.searchRoleText="";
$scope.searchRoleBtn=function(){
  $scope.GetroleList();
}

$scope.GetroleList=function(){
//  if ($scope.searchText) {
//   $scope.searchText=encodeURI($scope.searchText);
// }
$scope.isloading=true;
 if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
    if($scope.searchRoleText!=undefined){
$scope.searchRoleText=$scope.searchRoleText.replace(/\s+/g,"");
}
RS.personnelRole({searchText:$scope.searchRoleText,roleList:"",userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().roleStr }).then(function(Role){
 $scope.isloading=false;
 if (Role.errorcode=="0"&&Role.datas!=undefined) {
//将获取的部门数据加入到数据组中 注意筛选时清除数据

$scope.treedataRole=angular.copy(Role.datas);
//排序

$scope.treedataRole=$scope.treedataRole.sort(function(obj1,obj2){
  return obj1.wSort-obj2.wSort;
});
$scope.ApiData.allTreeOrg=$scope.treedataRole;
$scope.isShowData();
}else if (Role.errorcode!="0") {
}
}, function callback() {
  $scope.DataNull=false;
  Msg.error("请求数据有误");
  
});
}
$scope.isShowData=function(){

 if (!$scope.ApiData.allTreeOrg||$scope.ApiData.allTreeOrg.length<=0) {
  return true;
}else{

  return false;
}
}
$scope.currentTab="-1";
    //修改选中样式
    $scope.isActiveTab = function (tabUrl) {

     return tabUrl == $scope.currentTab;
   }
//展开或收缩
$scope.showSelectedcollapsedRole =function (scope,event,haschildren,index) {
  event.stopPropagation();
  scope.toggle();

  if (haschildren<=0) {
    $scope.SelectedModalRole(scope,event);
    return;
  }
   var nodeData = scope.$modelValue;//获取当前节点对象
//   console.log(nodeData);
if (!nodeData.children) {
  nodeData.children=[];
}
//  ||nodeData.children.length<nodeData.haschildren
   if(nodeData.children==null || nodeData.children.length<=0) //判定是否已经加载此对象子集数据
     {    $scope.currentTab = index;
      if($scope.ApiData.powerLV==undefined||$scope.ApiData.powerLV==null){
        $scope.ApiData.powerLV=sysUserInfo.getuserinfo().powerLV;
    }
      RS.personnelRole({searchText:"",roleList:nodeData,userId:sysUserInfo.getuserinfo().user_ID,organization_ID:sysUserInfo.getuserinfo().organization_ID,powerLV:$scope.ApiData.powerLV,forWhat:sysUserInfo.getuserinfo().roleStr }).then(function(Role){
        $scope.currentTab="";
        if (Role.errorcode=="0") {
          if (!Role.datas||Role.datas.length<=0) {
            Msg.warning("此节点暂无数据！");
          }else{
           $scope.DataNull=false;
         }
         nodeData.children=angular.copy(Role.datas);
            //排序
            nodeData.children=nodeData.children.sort(function(obj1,obj2){
              return obj1.wSort-obj2.wSort;
            }) 
          }else if (Role.errorcode!="0") {
          }
        }, function callback() {
          $scope.DataNull=false;
          Msg.error("请求数据有误");


        });
    }
  };

  $scope.containsRole = function(arr, obj) {  
    try {
     var i = arr.length;  
     while (i--) {  

      if (arr[i].roles_ID === obj.roles_ID) {  
        return i;  
      }  
    }  
    return -1; 
  } catch(e) {
        // statements
        return -1;
      }

    }
    
//选中触发方法
$scope.SelectedModalRole=function(scope,event){
  event.stopPropagation();
  if ($scope.ApiData.ViceRoleOpen) {
       //判断是否已选中次对象
       var result=$scope.containsRole($scope.ApiData.ViceuserRoleList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.ViceuserRoleList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.ViceuserRoleList.push(scope.$modelValue);
    }
  }else {
         //判断是否已选中次对象
         var result=$scope.containsRole($scope.ApiData.userRoleList,scope.$modelValue);
    if (result>-1) {//已选中的话 取消选中
     $scope.ApiData.userRoleList.splice(result,1);
    }else {//未选中 进行选中操作
      $scope.ApiData.userRoleList.push(scope.$modelValue);
    }
  }

}
//选中样式判断
$scope.IscheckModalRole=function(scope){
 if ($scope.ApiData.ViceRoleOpen) {
   var result=$scope.containsRole($scope.ApiData.ViceuserRoleList,scope.$modelValue);
   return result>-1;
 }else {
  var result=$scope.containsRole($scope.ApiData.userRoleList,scope.$modelValue);
  return result>-1;
}
}
$scope.GetroleList();
}]);


////****************************************************主页控制器 控制器调用服务***********************************/
//PensonSelector.controller("PensonSelectorController",['$scope','$localStorage', '$sessionStorage',
//  function($scope,$localStorage, $sessionStorage){

//  }]);
